package com.kun.listener;

import com.kun.common.constant.RedisConstant;
import com.kun.common.service.RedisService;
import com.kun.common.util.JsonUtils;
import com.kun.common.util.StringUtils;
import com.kun.domain.TUserFollowing;
import com.kun.domain.TUserMoments;
import com.kun.service.service.ITUserFollowingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(topic = "Topic-Moments", consumerGroup = "consumer-topic-moments")
public class RocketMQMomentsListener implements RocketMQListener<TUserMoments> {

    private final ITUserFollowingService itUserFollowingService;
    private final RedisService redisService;

    public RocketMQMomentsListener(ITUserFollowingService itUserFollowingService, RedisService redisService) {
        this.itUserFollowingService = itUserFollowingService;
        this.redisService = redisService;
    }

    @Override
    public void onMessage(TUserMoments tUserMoments) {
        log.info("接收到消息: {}", tUserMoments);
        // 获取粉丝
        List<TUserFollowing> userFans = itUserFollowingService.getUserFans(tUserMoments.getUserId());
        userFans.forEach(tUserFollowing -> {
            String key = RedisConstant.USER_FANS_KEY + tUserFollowing.getUserId();
            String serviceKey = redisService.getKey(key);
            List<TUserMoments> subscribedList;
            if (StringUtils.isEmpty(serviceKey)) {
                subscribedList = new ArrayList<>();
            } else {
                subscribedList = JsonUtils.toList(serviceKey, TUserMoments.class);
            }
            // 打印当前粉丝订阅的用户ID
            log.info("粉丝 ID: {} 正在订阅用户 ID: {}", tUserFollowing.getUserId(), tUserMoments.getUserId());
            subscribedList.add(tUserMoments);
            redisService.setKey(key, subscribedList);
        });
    }
}
